package com.wang.train.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.common.pojo.BasePojoEnum;
import com.wang.common.util.BeanUtil;
import com.wang.train.mapper.AtExamScoreDescMapper;
import com.wang.train.pojo.AtAnsSel;
import com.wang.train.pojo.AtAnsSelEnum;
import com.wang.train.pojo.AtAsk;
import com.wang.train.pojo.AtAskEnum;
import com.wang.train.pojo.AtAskQuery;
import com.wang.train.pojo.AtExamScoreDesc;
import com.wang.train.pojo.AtExamScoreDescEnum;
import com.wang.train.pojo.AtExamScoreDescQuery;
import com.wang.train.pojo.AtExamScoreDetail;
import com.wang.train.pojo.AtExamScoreDetailEnum;
import com.wang.train.pojo.AtExamScoreDetailQuery;
import com.wang.train.service.AtAskService;
import com.wang.train.service.AtExamScoreDescService;
import com.wang.train.service.AtExamScoreDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * 针对表【at_demo_dynasty(示例_考试结果概要表)】的数据库操作Service实现
 *
 * @author ZjxMi
 */
@Service
public class AtExamScoreDescServiceImpl extends ServiceImpl<AtExamScoreDescMapper, AtExamScoreDesc>
        implements AtExamScoreDescService {

    @Autowired
    private BeanUtil beanUtil;
    @Autowired
    private AtExamScoreDetailService examScoreDetailService;
    @Autowired
    private AtAskService askService;

    /**
     * model2: jsp --> servlet -->service --> dao --> db, 我们自己封装了一个 PageInfoUtil;
     * MybatisPlus: 不再需要调用 PageInfoUtil,老代码改造的时候是为了整合代码,如果没有老代码,直接写的新代码,采用下面的方式来搞
     *
     * @param page
     * @param query 查询对象
     * @return
     */
    @Override
    public List<AtExamScoreDesc> findList(IPage<AtExamScoreDesc> page, AtExamScoreDescQuery query) {
        if (page != null) {
            return this.baseMapper.findList(page, query);
        }
        return this.baseMapper.findList(query);
    }

    @Override
    public AtExamScoreDesc findOne(AtExamScoreDescQuery query) {
        AtExamScoreDesc one = this.baseMapper.findOne(query);
        if (Objects.nonNull(one)) {
            AtExamScoreDetailQuery detailQuery = new AtExamScoreDetailQuery();
            AtExamScoreDetail detailEntity = detailQuery.getEntity();
            detailEntity.setExamScoreId(one.getId());
            List<AtExamScoreDetail> scoreDetailList = this.examScoreDetailService.findList(null, detailQuery);
            one.setScoreDetailList(scoreDetailList);
        }
        return one;
    }

    @Override
    public int updateBatch(AtExamScoreDescQuery query) {
        return this.baseMapper.updateBatch(query);
    }

    @Override
    public int deleteBatch(AtExamScoreDescQuery query) {
        return this.baseMapper.deleteBatch(query);
    }

    /**
     * 对数据额外处理(非用户填写的数据)
     * @param entity
     */
    private void proccedUpdateData(AtExamScoreDesc entity){
        if (Objects.isNull(entity.getCreateTime())) {
            entity.setCreateTime(new Date());
        }
        entity.setUpdateTime(new Date());
        /* 判断对象是否为空 */
        if (Objects.isNull(entity.getPubTime())) {
            entity.setPubTime(new Date());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(AtExamScoreDesc entity) {
        /* 根据用户和卷子查询,只能有一个 */
        AtExamScoreDescQuery scoreDescQuery = new AtExamScoreDescQuery();
        AtExamScoreDesc scoreEntity = scoreDescQuery.getEntity();
        scoreEntity.setUsersId(entity.getUsersId());
        scoreEntity.setExamId(entity.getExamId());
        List<AtExamScoreDesc> scoreList = this.findList(null, scoreDescQuery);
        Assert.isTrue(scoreList.isEmpty(), "记录已经存在");

        this.proccedUpdateData(entity);
        /* 新增加的记录默认未删除 */
        entity.setDelFlag(BasePojoEnum.DELFLAG_NO.getCode());
        boolean dbFlag = super.save(entity);
        if (dbFlag) {
            int totalScore = 0 ;
            List<AtExamScoreDetail> scoreDetailList = entity.getScoreDetailList();
            for (AtExamScoreDetail dataTemp : scoreDetailList) {
                /* 查询askId对应的问题 */
                AtAskQuery askQuery = new AtAskQuery();
                AtAsk askEntity = askQuery.getEntity();
                askEntity.setId(dataTemp.getAskId());
                AtAsk ask = this.askService.findOne(askQuery);
                dataTemp.setName(ask.getName());
                dataTemp.setAskType(ask.getAskType());
                dataTemp.setCorrType(AtExamScoreDetailEnum.CORRTYPE_ERROR.getCode());

                if(AtAskEnum.ASKTYPE_PDT.getCode().equalsIgnoreCase(ask.getAskType())){
                    /* 去掉里面的逗号 */
                    String answer = dataTemp.getAnswer().replace(",", "");
                    /* 判断题 */
                    if (ask.getAnswer().indexOf(answer) != -1) {
                        /* 选择正确 */
                        dataTemp.setCorrType(AtExamScoreDetailEnum.CORRTYPE_CORRECT.getCode());
                    }
                } else {
                    /* 必须是单选题,多选题,判断题这三类题目才可以 */
                    /* 假如说是错误的 */
                    boolean multiFlag = true;
					/* if(ask.getAskType() == AAskEnum.ASKTYPE_SELECT.getStatus() || ask.getAskType() == AAskEnum.ASKTYPE_MULSELECT.getStatus()
									|| ask.getAskType() == AAskEnum.ASKTYPE_JUDGE.getStatus()) */
                    /* 判断用户的选项是否正确 */
                    for (Iterator iterator2 = ask.getAnsSelList().iterator(); iterator2.hasNext(); ) {
                        AtAnsSel selTemp = (AtAnsSel) iterator2.next();
                        /* 此选项必须正确 */
                        if (selTemp.getCorrType().equalsIgnoreCase(AtAnsSelEnum.CORRTYPE_CORRECT.getCode())) {
                            /* 判断用户的选项是否正确 */
                            if (ask.getAskType().equalsIgnoreCase(AtAskEnum.ASKTYPE_DANXT.getCode())) {
                                if (selTemp.getId().equalsIgnoreCase(dataTemp.getAnswerId())) {
                                    /* 选择正确 */
                                    dataTemp.setCorrType(AtAnsSelEnum.CORRTYPE_CORRECT.getCode());
                                    break;
                                }
                            } else if (ask.getAskType().equalsIgnoreCase(AtAskEnum.ASKTYPE_DUOXT.getCode())) {
                                /* 多选题;找不到,说明选择错误;直接退出,扣分 */
                                if (dataTemp.getAnswer().indexOf(selTemp.getId() + ",") == -1) {
                                    /* 选择正确 */
                                    multiFlag = false;
                                    break;
                                }
                            }
                        } else {
                            /* 错误 */
                            if (dataTemp.getAnswer().indexOf(selTemp.getId() + ",") != -1) {
                                /* 选择正确 */
                                multiFlag = false;
                                break;
                            }
                        }
                    }

                    if (multiFlag && ask.getAskType().equalsIgnoreCase(AtAskEnum.ASKTYPE_DUOXT.getCode())) {
                        /* 必须是多选,并且选择正确 */
                        dataTemp.setCorrType(AtAnsSelEnum.CORRTYPE_CORRECT.getCode());
                    }
                }

                if (dataTemp.getCorrType().equalsIgnoreCase(AtAnsSelEnum.CORRTYPE_CORRECT.getCode())) {
                    /* 正确,要算分 */
                    dataTemp.setScore(ask.getScore());
                    totalScore += ask.getScore();
                }
                dataTemp.setStatus(BasePojoEnum.STATUS_ENABLE.getCode());
                dataTemp.setExamScoreId(entity.getId());
                dataTemp.setPubTime(new Date());

                this.examScoreDetailService.save(dataTemp);
            }

            entity.setScore(totalScore);
            entity.setStatus(AtExamScoreDescEnum.STATUSNEW_GAICHENGJI.getCode());
            this.updateById(entity);
        }
        return dbFlag;
    }

    @Override
    public boolean updateById(AtExamScoreDesc entity) {
        /* 先根据id查询数据库的内容; */
        AtExamScoreDescQuery paramQuery = new AtExamScoreDescQuery();
        AtExamScoreDesc entityParam = paramQuery.getEntity();
        entityParam.setId(entity.getId());
        /* 数据库中查询的结果 */
        AtExamScoreDesc oneDbResult = this.findOne(paramQuery);
        /*
        * 源对象和目标对象是一个类型(10个字段)
        * 源对象有5个字段有值,目标对象是10个有值
        * 把源对象中的5个字段有值,赋值到目标对象中.(覆盖)
        * */
        oneDbResult = (AtExamScoreDesc) this.beanUtil.copy(entity, oneDbResult);

        this.proccedUpdateData(oneDbResult);
        return super.updateById(oneDbResult);
    }
}